<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录系统</title>
    <link rel="stylesheet" href="css/login.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <!-- 引入SHA256加密库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js"></script>

    <head>

    <body>
        <div class="container">
            <div class="decoration"></div>
            <div class="decoration"></div>

            <div class="header">
                <h1>欢迎回来</h1>
                <p>请登录您的账户以继续使用我们的服务</p>
            </div>

            <div class="form-container">
                <div class="left-panel">
                    <h2>登录账户的好处</h2>
                    <ul>
                        <li><i class="fas fa-check-circle"></i> 访问您的个人资料和设置</li>
                        <li><i class="fas fa-check-circle"></i> 查看您的历史记录和活动</li>
                        <li><i class="fas fa-check-circle"></i> 获取个性化推荐</li>
                        <li><i class="fas fa-check-circle"></i> 继续未完成的任务</li>
                        <li><i class="fas fa-check-circle"></i> 参与专属活动和优惠</li>
                        <li><i class="fas fa-check-circle"></i> 管理您的订阅和账户</li>
                    </ul>
                    <p>还没有账户? <a href="#" style="color: #4cc9f0; font-weight: 600;">立即注册</a></p>
                </div>

                <div class="right-panel">
                    <form id="loginForm">
                        <div class="form-group">
                            <label for="username"><i class="fas fa-user"></i> 用户名</label>
                            <input type="text" id="username" placeholder="输入您的用户名或者用户ID" autocomplete="username">
                        </div>

                        <div class="form-group">
                            <label for="password"><i class="fas fa-lock"></i> 密码</label>
                            <input type="password" id="password" placeholder="输入您的密码" autocomplete="current-password">
                        </div>

                        <div class="form-group">
                            <label for="role"><i class="fas fa-user-tag"></i> 角色</label>
                            <select id="role">
                                <option value="student" selected>学生</option>
                                <option value="teacher">教师</option>
                                <option value="admin">管理员</option>
                            </select>
                        </div>

                        <div class="remember-forgot">
                            <div class="remember">
                                <input type="checkbox" id="remember">
                                <label for="remember" style="margin:0; font-weight:400;">记住我</label>
                            </div>
                            <a href="#" class="forgot-password">忘记密码?</a>
                        </div>

                        <div id="messageContainer" class="message-container"></div>

                        <button type="submit" class="btn btn-primary" id="loginBtn">
                            <i class="fas fa-sign-in-alt"></i> 登录账户
                        </button>

                    </form>
                </div>
            </div>

            <div class="footer">
                登录即表示您同意我们的<a href="#">服务条款</a>和<a href="#">隐私政策</a>
            </div>
        </div>

        <script>
            // 获取DOM元素
            const loginForm = document.getElementById('loginForm');
            const loginBtn = document.getElementById('loginBtn');
            const messageContainer = document.getElementById('messageContainer');
            const usernameInput = document.getElementById('username');
            const passwordInput = document.getElementById('password');
            const roleSelect = document.getElementById('role');

            // 显示消息函数
            function showMessage(message, type) {
                messageContainer.textContent = message;
                messageContainer.className = "message-container";
                messageContainer.classList.add(`${type}-message`);

                // 3秒后自动消失
                if (type === 'error') {
                    setTimeout(() => {
                        messageContainer.style.display = 'none';
                    }, 3000);
                }
            }

            // 重置表单函数
            function resetForm() {
                loginForm.reset();
                roleSelect.value = "student"; // 重置为默认学生角色
                messageContainer.style.display = 'none';
            }

            // 页面跳转
            function redirectToDashboard(role, username) {
                // 定义角色对应的主页URL
                const roleUrls = {
                    student: 'student/dashboard.html',
                    teacher: 'teacher/dashboard.html',
                    admin: 'admin/dashboard.html'
                };

                // 检查角色是否有效
                if (roleUrls[role]) {
                    // 跳转到对应角色主页
                    window.location.href = roleUrls[role];
                } else {
                    // 默认跳转或错误处理
                    window.location.href = '/index.html';
                }
            }

            // 登录函数 - 使用Axios发送请求
            async function loginUser() {
                const username = usernameInput.value.trim();
                const password = passwordInput.value;
                const role = roleSelect.value;

                // 简单验证
                if (!username || !password) {
                    showMessage("用户名和密码不能为空", "error");
                    return;
                }

                // 密码加密
                const encryptedPassword = encryptPassword(password);

                // 显示加载状态
                loginBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 登录中...';
                loginBtn.disabled = true;

                try {
                    // 使用Axios发送登录请求
                    const response = await axios.post('/api/auth/login', {
                        username,
                        password: encryptedPassword, // 发送加密后的密码
                        role
                    });

                    // 检查响应状态
                    if (response.data.success) {
                        showMessage(`登录成功！欢迎回来，${response.data.user.name}`, "success");

                        // 保存用户信息到sessionStorage
                        localStorage.setItem('authToken', response.data.token);
                        sessionStorage.setItem('userToken', response.data.token);
                        sessionStorage.setItem('userRole', response.data.user.role);
                        sessionStorage.setItem('userInfo', JSON.stringify(response.data.user));

                        redirectToDashboard(role, username);
                    } else {
                        showMessage(response.data.message || "登录失败，请重试", "error");
                        passwordInput.value = "";
                    }
                } catch (error) {
                    // 错误处理
                    let errorMessage = "登录请求失败";

                    if (error.response) {
                        // 服务器返回了错误响应
                        if (error.response.data && error.response.data.message) {
                            errorMessage = error.response.data.message;
                        } else {
                            errorMessage = `服务器错误: ${error.response.status}`;
                        }
                    } else if (error.request) {
                        // 请求已发送但无响应
                        errorMessage = "无法连接到服务器，请检查网络";
                    } else {
                        // 请求配置错误
                        errorMessage = `请求配置错误: ${error.message}`;
                    }

                    showMessage(errorMessage, "error");
                    passwordInput.value = "";
                } finally {
                    // 重置按钮状态
                    loginBtn.innerHTML = '<i class="fas fa-sign-in-alt"></i> 登录账户';
                    loginBtn.disabled = false;
                }
            }

            // 密码加密函数
            function encryptPassword(password) {
                return sha256(password);
            }
            // 表单提交事件
            loginForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                await loginUser();
            });

            // @TODO: 模拟保存的cookie
            const rememberMe = localStorage.getItem('rememberMe');
            if (rememberMe === 'true') {
                document.getElementById('remember').checked = true;
                const savedUsername = localStorage.getItem('username');
                if (savedUsername) {
                    usernameInput.value = savedUsername;
                }
            }

            // 记住我功能
            document.getElementById('remember').addEventListener('change', function () {
                if (this.checked) {
                    localStorage.setItem('rememberMe', 'true');
                } else {
                    localStorage.removeItem('rememberMe');
                    localStorage.removeItem('username');
                }
            });

            // 输入用户名时保存
            usernameInput.addEventListener('input', function () {
                if (document.getElementById('remember').checked) {
                    localStorage.setItem('username', this.value);
                }
            });
        </script>
    </body>

</html>